package com.szxw.BaiduAi.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * @Author: 苏执小威
 * @Email:1410511702@qq.com
 * @Desc:
 * @Date: 2022/9/19 16:24
 */
public class DBUtils {
    private static DruidDataSource ds;

    static {
        Properties properties = new Properties();
        try {
            properties.load(DBUtils.class.getClassLoader().getResourceAsStream("database.properties"));
            //properties.load(new FileInputStream("D:\\Program Files (x86)\\shixun\\BaiduAi\\src\\main\\java\\com\\database.properties"));
            ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据源
     */
    public static DataSource getDataSource() {
        return ds;
    }

    /**
     * 获取数据连接
     */
    public static Connection getConnection() {
        try {
            return ds.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    /**
     * 开启事务手动提交
     */
    public static void begin() {
        Connection con = getConnection();
        try {
            con.setAutoCommit(false);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    /**
     * 事务提交
     */
    public static void commit() {
        Connection con = getConnection();
        try {
            con.commit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    /**
     * 事务回滚
     */
    public static void rollback() {
        Connection con = getConnection();
        try {
            con.rollback();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
